package com.xunmall.gateway.config;

import com.mongodb.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

@Configuration
@Component
public class MongoConfig extends AbstractMongoConfiguration {

	@Value("${spring.mongo.db.ip}")
	private String mongoIP;

	@Value("${spring.mongo.db.port}")
	private int mongoPort;

	@Value("${spring.mongo.db.sign}")
	private String dbNameSign;

	@Value("${spring.mongo.db.maxThreadCount}")
	private int maxThreadCount;

	@Bean
	public MongoClientOptions mongoClientOptions() {
		return MongoClientOptions.builder()
				.connectionsPerHost(128)
				.connectTimeout(30000)
				.threadsAllowedToBlockForConnectionMultiplier(this.maxThreadCount)
				.maxConnectionIdleTime(60000)
				.maxWaitTime(10000)
				.writeConcern(WriteConcern.MAJORITY)
				.build();
	}

	@Override
	@Bean
	public Mongo mongo() {
		return new MongoClient(new ServerAddress(this.mongoIP, this.mongoPort),
				this.mongoClientOptions());
	}

	@Bean(name = "signTemplate")
	public MongoTemplate getMongoSignTemplate() {
		return new MongoTemplate(this.mongo(),
				this.dbNameSign);
	}

	@Override
	protected String getDatabaseName() {
		return this.dbNameSign;
	}

}
